import matplotlib.pyplot as plt
from io import BytesIO
from urllib.request import urlopen
import tarfile
import numpy as np
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable

# def add_titlebox(ax, text):
#     ax.text(.55, .8, text,
#             horizontalalignment='center',
#             transform=ax.transAxes,
#             bbox=dict(facecolor='white', alpha=0.6),
#             fontsize=12.5)
#     return ax
#
#
# url = 'http://www.dcc.fc.up.pt/~ltorgo/Regression/cal_housing.tgz'
# b = BytesIO(urlopen(url).read())
# fpath = 'CaliforniaHousing/cal_housing.data'
#
# with tarfile.open(mode='r', fileobj=b) as archive:
#     housing = np.loadtxt(archive.extractfile(fpath), delimiter=',')
#     y = housing[:, -1]
#     pop, age = housing[:, [4, 7]].T
#
#     gridsize = (3, 2)
#     fig = plt.figure(figsize=(12, 8))
#     ax1 = plt.subplot2grid(gridsize, (0, 0), colspan=2, rowspan=2)
#     ax2 = plt.subplot2grid(gridsize, (2, 0))
#     ax3 = plt.subplot2grid(gridsize, (2, 1))
#
#     ax1.set_title('Home value as a function of home age & area population', fontsize=14)
#     sctr = ax1.scatter(x=age, y=pop, c=y, cmap='RdYlGn')
#     plt.colorbar(sctr, ax=ax1, format='$%d')  # 彩色渐变条
#     ax1.set_yscale('log')
#
#     ax2.hist(age, bins='auto')
#     ax3.hist(pop, bins='auto', log=True)
#
#     add_titlebox(ax2, 'Histogram: home age')
#     add_titlebox(ax3, 'Histogram: area population (log scl.)')
#
# plt.show()
# plt.close()  # 关闭当前figure
# # plt.close(num)  # 关闭指定编号的figure,num 从1开始
# plt.close('all')  # 关闭所有
#
#
sides = ('left', 'right', 'top', 'bottom')  # 定义一个元组
nolabels = {s: False for s in sides}  # 初始化字典

print(nolabels)  # {'left': False, 'right': False, 'top': False, 'bottom': False}
nolabels.update({'label%s' % s: False for s in sides})

# {'left': False, 'right': False, 'top': False, 'bottom': False, 'labelleft': False, 'labelright': False, 'labeltop': False, 'labelbottom': False}
print(nolabels)

x = np.diag(np.arange(2, 12))[::-1]  # [::-1] 各个维度元素反转
x[np.diag_indices_from(x[::-1])] = np.arange(2, 12)
x2 = np.arange(x.size).reshape(x.shape)

with plt.rc_context(rc={'axes.grid': False}):
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))
    ax1.matshow(x)
    img2 = ax2.matshow(x2, cmap='RdYlGn_r')
    for ax in (ax1, ax2):
        ax.tick_params(axis='both', which='both', **nolabels)
    for i, j in zip(*x.nonzero()):
        ax1.text(j, i, x[i, j], color='white', ha='center', va='center')

    divider = make_axes_locatable(ax2)
    cax = divider.append_axes("right", size='5%', pad=0)
    plt.colorbar(img2, cax=cax, ax=[ax1, ax2])
    fig.suptitle('Heatmaps with `Axes.matshow`', fontsize=16)
plt.show()
